package com.haoqizhe.kernel.mybatisplus.apiscanner.scanner;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.haoqizhe.kernel.mybatisplus.apiscanner.properties.ApiScannerProperties;
import com.haoqizhe.kernel.commons.util.SpringContextUtil;
import com.haoqizhe.kernel.mybatisplus.apiscanner.dto.SysInterface;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.HttpMethod;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Api接口扫描器
 *
 * @author haoqizhe.li
 * @date 2021/01/22 18:46
 */
@Slf4j
@Component
@EnableConfigurationProperties(ApiScannerProperties.class)
@ConditionalOnProperty(prefix = "api.scanner", name = "enabled", havingValue = "enabled", matchIfMissing = false)
public class ApiScanner {
    @Autowired
    private ApiScannerProperties properties;
    /**
     * 系统名称
     */
    @Value("${spring.application.name:#{'unknown'}}")
    private String platformCode;
    /**
     * 系统接口前缀
     */
    @Value("${server.servlet.context-path:#{''}}")
    private String serverPath;

    /**
     * 扫描获取系统中所有Controller类的接口信息
     */
    public List<SysInterface> scanApiListing() {
        List<SysInterface> result = new ArrayList<>();

        // 获取spring容器中所有Bean 的名称（因为所有bean都会继承Object）
        String[] beanNames = SpringContextUtil.getApplicationContext().getBeanNamesForType(Object.class);

        // 遍历所有bean,判断其是否是控制器类 如果是，开始扫描bean中的接口
        int beanCount = beanNames.length;
        List<String> apiPathList = new ArrayList<>();
        for (int i = 0; i < beanCount; i++) {
            String beanName = beanNames[i];

            // 如果bean前缀带有目标对象的标识  则不会是我们要找的Controller类
            // apiResourceController swagger api
            if (!beanName.startsWith("scopedTarget.") && !"apiResourceController".equals(beanName)) {
                Class beanType = null;
                try {
                    // 根据bean名称获取bean的类型
                    beanType = SpringContextUtil.getApplicationContext().getType(beanName);
                } catch (Throwable ex) {
                    log.error(ex.getMessage(), ex);
                    continue;
                }

                // 判断bean是否包含Controller或者RequestMapping注解,如果是 就可以在其中找到接口
                if (beanType != null && this.isHandler(beanType)) {
                    // 接口地址前缀
                    String preUrl = "";

                    // 获取类上的注解信息
                    RequestMapping requestMapping = AnnotationUtils.findAnnotation(beanType, RequestMapping.class);
                    if (requestMapping != null && requestMapping.value().length > 0) {
                        preUrl = requestMapping.value()[0];
                    }

                    // swaggerUI相关注解
                    String moduleName = "";
                    Api api = AnnotationUtils.findAnnotation(beanType, Api.class);
                    if (api != null) {
                        moduleName = api.value();
                    }

                    // 获取类中的接口方法的注解信息
                    Method[] methods = beanType.getMethods();
                    // 用来判断是否存在同url的方法（子类重写父类接口方法时会出现），出现同url接口方法，只记录第一个就可以，因为信息完全一样
                    for (Method method : methods) {

                        // 接口方法访问修饰符应为public
                        if (Modifier.isPublic(method.getModifiers())) {
                            String methodUrl = "";
                            String[] methodUrls = new String[0];
                            String apiMapping = "";

                            // 方法上的地址映射注解 可能为  GetMapping PostMapping RequestMapping PutMapping DeleteMapping PatchMapping
                            GetMapping getMapping = AnnotationUtils.findAnnotation(method, GetMapping.class);
                            PostMapping postMapping = AnnotationUtils.findAnnotation(method, PostMapping.class);
                            PutMapping putMapping = AnnotationUtils.findAnnotation(method, PutMapping.class);
                            DeleteMapping deleteMapping = AnnotationUtils.findAnnotation(method, DeleteMapping.class);
                            PatchMapping patchMapping = AnnotationUtils.findAnnotation(method, PatchMapping.class);
                            RequestMapping methodRequestMapping = AnnotationUtils.findAnnotation(method, RequestMapping.class);
                            if (getMapping != null) {
                                apiMapping = HttpMethod.GET.name();
                                methodUrls = getMapping.value();
                            } else if (postMapping != null) {
                                apiMapping = HttpMethod.POST.name();
                                methodUrls = postMapping.value();
                            } else if (putMapping != null) {
                                apiMapping = HttpMethod.PUT.name();
                                methodUrls = putMapping.value();
                            } else if (deleteMapping != null) {
                                apiMapping = HttpMethod.DELETE.name();
                                methodUrls = deleteMapping.value();
                            } else if (patchMapping != null) {
                                apiMapping = HttpMethod.PATCH.name();
                                methodUrls = patchMapping.value();
                            } else if (methodRequestMapping != null) {
                                apiMapping = "request";
                                methodUrls = methodRequestMapping.value();
                            }

                            // 如果方法上的地址地址映射不为空，就代表方法是接口方法
                            if (methodUrls.length > 0 || (postMapping != null && methodUrls.length == 0)) {
                                methodUrl = "";
                                if (methodUrls.length > 0) {
                                    // 取第一个值作为方法url
                                    methodUrl = methodUrls[0];
                                }

                                // 接口最终的路径 系统前缀（配置文件）+前缀(控制器上)+后缀（方法上）
                                String apiPath = getApiPath(preUrl, methodUrl);
                                String key = apiMapping + " " + apiPath;
                                if (apiPathList.contains(key) || !isNeedToSaveApiPath(apiPath)) {
                                    continue;
                                } else {
                                    apiPathList.add(key);
                                }

                                // swaggerUI相关注解
                                String apiName = "";
                                String apiDesc = "";
                                ApiOperation apiOperation = AnnotationUtils.findAnnotation(method, ApiOperation.class);
                                if (apiOperation != null) {
                                    String methodName = method.getName();
                                    apiName = apiOperation.value().length() == 0 ? methodName : apiOperation.value();
                                    apiDesc = apiOperation.notes();
                                }

                                // shiro权限标签
                                String shiroLab = "";
                                RequiresPermissions requiresPermissions = AnnotationUtils.findAnnotation(method, RequiresPermissions.class);
                                if (requiresPermissions != null) {
                                    String[] tags = requiresPermissions.value();
                                    if (tags != null && tags.length > 0) {
                                        for (String tag : tags) {
                                            shiroLab += (tag + ",");
                                        }
                                        shiroLab = shiroLab.substring(0, shiroLab.length() - 1);
                                    }
                                }

                                // security权限标签
                                String securityLab = "";
                                PreAuthorize preAuthorize = AnnotationUtils.findAnnotation(method, PreAuthorize.class);
                                if (preAuthorize != null) {
                                    String value = preAuthorize.value();
                                    if (value.contains("hasAnyRole")) {
                                        String temp = value.replace("hasAnyRole", "");
                                        temp = temp.substring(2, temp.length() - 2);
                                        securityLab = temp;
                                    }
                                }

                                // 构建 接口信息实体 放到结果列表

                                String crc = platformCode + moduleName + apiMapping + apiPath;

                                SysInterface sysInterface = new SysInterface();
                                sysInterface.setPlatformCode(platformCode);
                                sysInterface.setModuleCode(beanName);
                                sysInterface.setModuleName(moduleName);
                                sysInterface.setApiCode(method.getName());
                                sysInterface.setApiName(apiName);
                                sysInterface.setApiMapping(apiMapping);
                                sysInterface.setApiDesc(apiDesc);
                                sysInterface.setApiPath(apiPath);
                                sysInterface.setShiroLab(shiroLab);
                                sysInterface.setSecurityLab(securityLab);
                                sysInterface.setCrc(SecureUtil.md5(crc));
                                result.add(sysInterface);
                            }
                        }
                    }
                }
            }
        }
        return result;
    }

    /**
     * 判断 某个类判断该类是否包含Controller或者RequestMapping注解
     *
     * @param beanType
     * @return
     */
    protected boolean isHandler(Class<?> beanType) {
        return AnnotatedElementUtils.hasAnnotation(beanType, Controller.class) ||
                AnnotatedElementUtils.hasAnnotation(beanType, RequestMapping.class) ||
                AnnotatedElementUtils.hasAnnotation(beanType, RestController.class);
    }

    /**
     * 判断接口路径是否需要记录
     *
     * @param apiPath 接口路径
     */
    private boolean isNeedToSaveApiPath(String apiPath) {
        // 先获取配置文件中的  需要忽略的url列表
        List<String> ignoreUrlList = getIgnoreUrlList();
        // 如果请求的url在需要忽略url列表里  则返回false，不需要记录日志
        for (String ignoreUrl : ignoreUrlList) {
            if (apiPath.contains(ignoreUrl)) {
                return false;
            }
        }
        return true;
    }


    /**
     * 获取需要忽略的url列表（可配置）
     */
    private List<String> getIgnoreUrlList() {
        List<String> ignoreUrlList = new ArrayList();
        if (StrUtil.isNotBlank(properties.getIgnoreUrls())) {
            ignoreUrlList.addAll(Arrays.asList(properties.getIgnoreUrls().split(",")));
        }
        return ignoreUrlList;
    }

    /**
     * 接口路径
     *
     * @param preUrl    控制器路径
     * @param methodUrl 方法路径
     * @return
     */
    private String getApiPath(String preUrl, String methodUrl) {
        String path = StrUtil.isNotBlank(serverPath) ? serverPath.endsWith("/") ? serverPath : serverPath + "/" : "";
        preUrl = StrUtil.isNotBlank(preUrl) ? preUrl.endsWith("/") ? preUrl : preUrl + "/" : "";
        methodUrl = path + preUrl + methodUrl;
        return methodUrl.replaceAll("//", "/");
    }
}
